# api_client.py
# utils/logger.py
import logging
from logging.config import dictConfig
import yaml
from googleapiclient.discovery import build
# main.py 或 captureRV.py 中
from models.comment_schema import RVVideo

class YouTubeClient:
    def __init__(self, api_key):
        self.service = build('youtube', 'v3', developerKey=api_key)
        
    def search_videos(self, keyword, max_results=50):
        return self.service.search().list(
            q=keyword,
            part="id,snippet",
            maxResults=max_results,
            type="video"
        ).execute()
    


with open('config/logging.yaml') as f:
    config = yaml.safe_load(f)
    dictConfig(config)

logger = logging.getLogger(__name__)


class RVVideoCollector:
    def __init__(self, api_key):
        self.api_key = api_key
        self.youtube = build('youtube', 'v3', developerKey=api_key)

    def collect_videos(self, keyword, max_results=100):
        """通过关键词搜索视频"""
        try:
            search_response = self.youtube.search().list(
                q=keyword,
                part="id,snippet",
                maxResults=max_results,
                type="video",
                order="viewCount"
            ).execute()

            items = []
            for item in search_response.get('items', []):
                video_id = item['id']['videoId']
                snippet = item['snippet']
                title = snippet['title']

                # 构造 ORM 实例
                items.append(RVVideo(
                    video_id=video_id,
                    title=title,
                    view_count=0  # 示例值，你可以从 API 获取统计信息
                ))
            return items
        except Exception as e:
            logging.error(f"搜索视频时出错: {str(e)}")
            return []